<template>
  <div>
    <!-- bannerform表示的是调用规则 -->
    <el-form
      label-width="100px"
      :model="formData"
      :rules="rules"
      ref="bannerForm"
      
    >
      <el-form-item label="图片" prop="img">
        <el-upload
          ref="upload"
          :limit="1"
          :auto-upload="false"
          list-type="picture"
          :on-exceed="onExceed"
          :on-change="onChange"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="图片文案" prop="alt">
        <el-input v-model="formData.alt" />
      </el-form-item>
      <el-form-item label="跳转链接" prop="link">
        <el-input v-model="formData.link" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { genFileId } from 'element-plus'

import { addBanner } from '../services/index'
export default {
  emits: ['on-add-succuss'],
  data() {
    return {
      formData: {
        img: '',
        alt: '',
        link: '',
      },
      rules: {
        img: [
          { required: true, trigger: 'blur', message: '请选择图片' }
        ],
        alt: [
          { required: true, trigger: 'blur', message: '请选择图片' }
        ],
        link: [
          { required: true, trigger: 'blur', message: '请选择图片' }
        ],
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.bannerForm.validate((valid) => { 
        if (valid) {
          // 添加 轮播图
          addBanner(this.formData).then((result) => {
            // console.log(result);
            // 通知父组件 添加成功
            this.$emit('on-add-succuss')
            // 清空
            this.$refs.bannerForm.resetFields()
            this.$refs.upload.clearFiles()
          })
        }
      })
    },
    // 如果已上传文件，再次上传文件时，应该清掉之前的
    onExceed(files) {
      const uploadRef = this.$refs.upload

      uploadRef.clearFiles()

      const file = files[0]
      file.uid = genFileId()

      uploadRef.handleStart(file)
    },
    // 把文件转化为 base64 字符串
    onChange(file) {
      const fileReader = new FileReader()
      fileReader.onload = () => {
        // 将 base64 字符串，赋值给 form.img
        this.formData.img = fileReader.result
      }
      fileReader.readAsDataURL(file.raw)
    }
  }
}
</script>